package comum;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;

/**
 * @author gbomfim
 * Classe utilitaria para envio de pacotes TCP entre o cliente e o Servidor, com um padrao de mensagem definida.
 *
 */
public class Pacote {
	
	protected String type;
	protected String path;
	protected String content;
	protected String response = "";
	
	public String getResponse() {
		return response;
	}

	public void setResponse(String response) {
		this.response = response;
	}

	public Pacote (String type, String path, String content) {
		this.setType(type);
		this.setPath(path);
		this.setContent(content);
	}

	public String getType() {
		return type;
	}

	public void setType(String type) {
		if(type.contains("type->")) { type = type.split("->")[1]; }
		this.type = type;
	}

	public String getPath() {
		return path;
	}

	public void setPath(String path) {
		if(path.contains("path->")) { path = path.split("->")[1]; }
		this.path = path;
	}

	public String getContent() {
		return content;
	}

	public void setContent(String content) {
		if(content.contains("content->")) { content = content.split("->", 2)[1]; }
		this.content = content;
	}
	
	
	/**
	 * Retorno a concatenacao de todos o atributos da classe, para montarmos a mensagem para envio via TCP
	 * @return
	 */
	protected String getFullMessage() {
		String message = "type->"+this.getType()+"\n";
		message += "path->"+this.getPath()+"\n";
		message += "content->"+this.getContent()+"\nend\n";
		return message;
	}
	
	/**
	 * Monto o pacote TCP e envio, a partir dos parametros de IP e Port passados, referentes ao servidor de destino.
	 * O metodo se utiliza dos proprios atributos da classe para montar a mensagem.
	 * @param ip
	 * @param port
	 * @return
	 */
	public boolean sendTo(String ip, Integer port) {
		System.out.println("Enviando pacote");
		Socket socket;
		try {
			System.out.println(ip +"    "+ port);
			socket = new Socket(ip, port);
			
			PrintWriter out = new PrintWriter(socket.getOutputStream(), true);

			out.println(this.getFullMessage());
			
			String inputline = "";
			
			BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
			while ((inputline = in.readLine()) != null) {
				this.response  += inputline +"\n";	
			}
			
			out.close();
			in.close();
			socket.close();
			
			return true;
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}
	}
	
}
